<template>
  <div class="app-container" v-loading="pageLoading" element-loading-text="加载中...">
    <el-card shadow="never" v-if="!pageLoading">
      <div slot="header" class="clearfix">
        <span>执行盘点</span>
      </div>
      
      <!-- 基本信息 -->
      <div class="info-section">
        <h3>基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>计划日期：</label>
              <span>{{ parseTime(inventoryInfo.plannedDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>备件仓库：</label>
              <span>{{ getWarehouseName(inventoryInfo.warehouseCode) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>盘点人：</label>
              <span>{{ inventoryInfo.inventoryUser }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="16">
            <div class="info-item">
              <label>备注：</label>
              <el-input
                v-model="inventoryInfo.remark"
                type="textarea"
                :rows="2"
                placeholder="请输入备注"
                style="width: 300px;"
              />
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 备件信息 -->
      <div class="info-section" style="margin-top: 30px;">
        <h3>备件信息</h3>
        <el-table :data="partList" border>
          <el-table-column label="备件编号" align="center" prop="partNo" width="150" />
          <el-table-column label="备件名称" align="center" prop="partName" min-width="200" />
          <el-table-column label="规格型号" align="center" prop="specNo" width="120" />
          <el-table-column label="备件类型" align="center" prop="partTypeCode" width="100">
            <template slot-scope="scope">
              <span>{{ getPartTypeName(scope.row.partTypeCode) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="理论在库数" align="center" prop="theoreticalQty" width="120" />
          <el-table-column label="实际在库数" align="center" width="200">
            <template slot-scope="scope">
              <div class="quantity-control">
                <el-button 
                  size="mini" 
                  icon="el-icon-minus" 
                  @click="decreaseQuantity(scope.row)"
                  :disabled="scope.row.actualQty <= 0"
                  circle
                ></el-button>
                <el-input-number
                  v-model="scope.row.actualQty"
                  :min="0"
                  :precision="0"
                  size="small"
                  @change="calculateDifference(scope.row)"
                  style="width: 80px; margin: 0 5px;"
                  controls-position="right"
                />
                <el-button 
                  size="mini" 
                  icon="el-icon-plus" 
                  @click="increaseQuantity(scope.row)"
                  circle
                ></el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="盘盈数量" align="center" width="120">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.surplusQty > 0 ? '#67C23A' : '#909399' }">
                {{ scope.row.surplusQty > 0 ? '+' + scope.row.surplusQty : scope.row.surplusQty }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="盘亏数量" align="center" width="120">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.lossQty > 0 ? '#F56C6C' : '#909399' }">
                {{ scope.row.lossQty > 0 ? '-' + scope.row.lossQty : scope.row.lossQty }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div style="text-align: right; margin-top: 20px;">
        <el-button @click="$router.back()">返 回</el-button>
        <el-button type="primary" @click="handleSubmit">提 交</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getInventory, executeInventory } from '@/api/inventory/inventory'
import { formatDateTime } from '@/utils/ruoyi'

export default {
  name: 'InventoryExecute',
  data() {
    return {
      sessionNo: '',
      inventoryInfo: {},
      partList: [],
      warehouseOptions: [],
      partTypeOptions: [],
      pageLoading: true
    }
  },
  async created() {
    this.sessionNo = this.$route.params.sessionNo
    try {
      // 先加载字典，再加载详情，避免映射后跳
      await Promise.all([this.loadWarehouses(), this.loadPartTypes()])
      await this.getDetail()
    } finally {
      this.pageLoading = false
    }
  },
  methods: {
    // 加载仓库列表
    loadWarehouses() {
      if (this.$apiWarehouseLoaded) return
      import('@/api/inventory/warehouse').then(mod => {
        const listFn = mod.listWarehouseDTO || mod.listWarehouse || mod.list
        listFn && listFn({ pageNum: 1, pageSize: 9999 }).then(res => {
          this.warehouseOptions = res.data || res.rows || []
          this.$apiWarehouseLoaded = true
        })
      }).catch(() => {})
    },
    // 加载备件类型列表
    loadPartTypes() {
      if (this.$apiPartTypeLoaded) return
      import('@/api/dict/partType').then(mod => {
        const listFn = mod.listPartType || mod.list
        if (listFn) {
          listFn({ pageNum: 1, pageSize: 9999, enabled: 1 }).then(res => {
            this.partTypeOptions = res.rows || res.data || []
            this.$apiPartTypeLoaded = true
          })
        }
      }).catch(() => {})
    },
    // 获取详情
    getDetail() {
      return getInventory(this.sessionNo).then(res => {
        this.inventoryInfo = res.data
        this.partList = (res.data.partList || []).map(item => ({
          ...item,
          actualQty: item.actualQty || item.theoreticalQty,
          surplusQty: 0,
          lossQty: 0
        }))
        // 初始化时计算差值
        this.partList.forEach(item => {
          this.calculateDifference(item)
        })
      }).catch(error => {
        console.error('获取详情失败:', error)
        this.$message.error('获取盘点详情失败')
      })
    },
    // 增加数量
    increaseQuantity(row) {
      row.actualQty = (row.actualQty || 0) + 1
      this.calculateDifference(row)
    },
    // 减少数量
    decreaseQuantity(row) {
      if (row.actualQty > 0) {
        row.actualQty = row.actualQty - 1
        this.calculateDifference(row)
      }
    },
    // 计算盘盈盘亏
    calculateDifference(row) {
      const theoretical = row.theoreticalQty || 0
      const actual = row.actualQty || 0
      const difference = actual - theoretical
      
      row.surplusQty = difference > 0 ? difference : 0
      row.lossQty = difference < 0 ? Math.abs(difference) : 0
    },
    // 提交盘点结果
    handleSubmit() {
      if (this.partList.some(item => item.actualQty == null)) {
        this.$message.warning('请填写所有备件的实际在库数')
        return
      }

      const payload = {
        sessionNo: this.sessionNo,
        actualDate: formatDateTime(new Date()),
        remark: this.inventoryInfo.remark,
        partList: this.partList.map(({ partNo, actualQty, surplusQty, lossQty }) => ({
          partNo, actualQty, surplusQty, lossQty
        }))
      }

      executeInventory(payload).then(() => {
        this.$message.success('盘点完成')
        setTimeout(() => {
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.back()
        }, 500)
      }).catch(error => {
        console.error('提交失败:', error)
        this.$message.error('盘点失败')
      })
    },
    /** 获取仓库名称 */
    getWarehouseName(code) {
      const warehouse = this.warehouseOptions.find(w => w.warehouseCode === code)
      return warehouse ? warehouse.warehouseName : code
    },
    /** 获取备件类型名称 */
    getPartTypeName(code) {
      if (!code) return '';
      const partType = this.partTypeOptions.find(type => type.code === code);
      return partType ? partType.name : code;
    }
  }
}
</script>

<style scoped>
.info-section {
  margin-bottom: 20px;
}

.info-section h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.info-item {
  margin-bottom: 10px;
}

.info-item label {
  font-weight: 600;
  color: #606266;
  margin-right: 10px;
}

.info-item span {
  color: #303133;
}

.quantity-control {
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity-control .el-button {
  margin: 0 2px;
}

.quantity-control .el-button.is-disabled {
  opacity: 0.5;
}
</style>
